'use strict';

const BaseController = require('./BaseController');
class RegisterController extends BaseController {
  async index() {
    const { ctx, app } = this;
    let query = ctx.request.body;
    if(query){
      const tempJson = await ctx.service.register.checkUsername({username:query.username,name:query.name,password:query.password},this);
      if(tempJson.code===1){
        try{
          let user = ctx.model.User.build()
          const res = await this.ctx.curl('https://apis.map.qq.com/ws/location/v1/ip?key=IQSBZ-RDHWR-SG5WC-WBL6E-EXSDK-B7BNS&ip='+ctx.request.ip);
          if(res.status===0){
            user.nation = res.result.ad_info.nation;
            user.province = res.result.ad_info.province;
            user.city = res.result.ad_info.city;
            user.district = res.result.ad_info.district;
            user.adcode = res.result.ad_info.adcode
          }
          user.name = query.name;
          user.username = query.username;
          user.password = query.password;
          user.ip = ctx.request.ip
          user.name = query.name;
          await ctx.model.User.create(user.dataValues);
          ctx.body = {code:1,msg:"注册成功"}
        }catch(e){
          console.error(`\x1B[36m 时间：${this.parseTime(Date.now())}\x1B[0m`,`\x1B[31m注册接口异常：${e}\x1B[0m`,`\x1B[33m 参数：${JSON.stringify(query)}\x1B[0m`)
          ctx.body = {code:0,msg:"注册异常"}
        }
      }else{
        ctx.body = tempJson
      }
    }else{
      ctx.body = {code:0,msg:"请输入正确的格式"};
    }
  }
  async checkUsername(){
    const { ctx, app } = this;
    let result = await ctx.service.register.checkUsername(ctx.request.body,this);
    ctx.body = result;
  }
}

module.exports = RegisterController;
